const router = require('koa-router')(); //引入router 并调用
const {postLogData} =require("../utils/misc")
const ObjectId = require('mongodb').ObjectId

const mongo = require('../compents/mongo')
// 设置根路径
router.prefix('/role')

// 获取数据
router.get('/list', async ctx => {
    postLogData("请求角色数据")
    let { limit, page, where } = ctx.query
    const res = await mongo.find('role', { limit: limit * 1, page: page * 1 })
    const total = await mongo.count('role', { where })
    ctx.body = { data: res, code: 20000, total, message: "端口求成功" }
})

// 插入数据
router.post('/save', async ctx => {
    postLogData("插入角色数据")
    const res = await mongo.insertOne("role", ctx.request.body)
    if (res.insertedId) {
        ctx.body = { data: res, msg: "新增数据成功", code: 20000 }
    } else {
        ctx.body = { data: res, msg: "新增数据失败", code: 50001 }

    }
})

// 修改数据
router.post('/update', async ctx => {
    postLogData("修改角色数据")
    const { _id } = ctx.request.body
    const update = { ...ctx.request.body };
    delete update._id
    const res = await mongo.updateOne('role', { where: { _id: ObjectId(_id) }, update })
    if (res.modifiedCount > 0) {
        ctx.body = { code: 20000, msg: '数据修改成功', success: true }
    } else {
        ctx.body = { code: 50002, msg: '数据修改失败', success: false }
    }
})

// 单个删除
router.get('/delete', async ctx => {
    postLogData("单删角色数据")
    const { _id } = ctx.query
    const res = await mongo.deleteOne('role', { _id: ObjectId(_id) })
    ctx.body = { code: 20000, msg: '数据删除成功', success: true }
})

// 批量删除
router.get('/deleteMany', async ctx => {
    postLogData("多删角色数据")
    let { ids } = ctx.query
    ids = ids.split(',')
    const res = await mongo.deleteMany('role', ids)
    ctx.body = { code: 20000, msg: '数据删除成功', success: true }
})

// 查询
router.get('/search', async ctx => {
    let { id } = ctx.query
    let where = { _id: ObjectId(id) }
    const res = await mongo.findOne('role', where)
    console.log(res);
    ctx.body = { code: 20000, data: res, message: '接口请求成功' }
})

module.exports = router